import { UserProfile, PointsTransaction, UserListResponse } from '../types';

const API_BASE = '/api';

// 用户统计数据接口
export interface UserStats {
  id: number;
  userId: number;
  uploadBytes: number;
  downloadBytes: number;
  point: number;
  lastSeedingUpdate: string;
  ratio: number;
}

export class UserService {
  private static getHeaders() {
    const token = localStorage.getItem('token');
    return {
      'Content-Type': 'application/json',
      'Authorization': token ? `Bearer ${token}` : ''
    };
  }

  static async getCurrentUserProfile(): Promise<UserProfile> {
    const response = await fetch(`${API_BASE}/auth/profile`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw { type: 'auth', code: error.message || 'UNKNOWN_ERROR' };
    }

    return response.json();
  }

  static async getUserProfile(username: string): Promise<UserProfile> {
    // 由于后端没有实现/users/{username}接口，暂时使用/auth/profile接口获取当前用户信息
    const response = await fetch(`${API_BASE}/auth/profile`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw { type: 'auth', code: error.message || 'UNKNOWN_ERROR' };
    }

    return response.json();
  }

  // 获取用户统计数据（上传量、下载量、分享率）
  static async getUserStats(): Promise<UserStats> {
    try {
      const response = await fetch(`${API_BASE}/point/getPoint`, {
        method: 'GET',
        headers: this.getHeaders(),
      });

      if (!response.ok) {
        console.error('获取用户统计数据失败，状态码:', response.status);
        throw new Error(`获取用户统计数据失败: ${response.statusText}`);
      }

      const data = await response.json();
      console.log('获取用户统计数据成功，返回数据:', data);
      
      return data;
    } catch (error) {
      console.error('获取用户统计数据出错:', error);
      // 返回默认值
      return {
        id: 0,
        userId: 0,
        uploadBytes: 0,
        downloadBytes: 0,
        point: 0,
        lastSeedingUpdate: new Date().toISOString(),
        ratio: 0
      };
    }
  }

  static async getAllUsers(page: number = 1, pageSize: number = 10): Promise<UserListResponse> {
    const response = await fetch(`${API_BASE}/users?page=${page}&pageSize=${pageSize}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw { type: 'auth', code: error.message || 'UNKNOWN_ERROR' };
    }

    return response.json();
  }

  static async updateUserProfile(username: string, data: Partial<UserProfile>): Promise<UserProfile> {
    const response = await fetch(`${API_BASE}/users/${username}`, {
      method: 'PUT',
      headers: this.getHeaders(),
      body: JSON.stringify(data)
    });

    if (!response.ok) {
      const error = await response.json();
      throw { type: 'auth', code: error.message || 'UNKNOWN_ERROR' };
    }

    return response.json();
  }

  static async getUserPoints(username: string): Promise<number> {
    const response = await fetch(`${API_BASE}/users/${username}/points`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw { type: 'auth', code: error.message || 'UNKNOWN_ERROR' };
    }

    const data = await response.json();
    return data.points;
  }

  static async getCurrentUserPoints(): Promise<number> {
    console.log('开始获取当前用户积分');
    try {
      const response = await fetch('/api/point/getPoint', {
        method: 'GET',
        headers: this.getHeaders(),
      });

      if (!response.ok) {
        console.error('获取积分失败，状态码:', response.status);
        throw new Error(`获取积分失败: ${response.statusText}`);
      }

      const data = await response.json();
      console.log('获取积分成功，返回数据:', data, '类型:', typeof data);
      
      // 确保返回数字类型
      if (typeof data === 'number') {
        return data;
      } else if (data && typeof data === 'object') {
        // 尝试从对象中提取数字
        if ('points' in data) return Number(data.points);
        if ('point' in data) return Number(data.point);
        if ('data' in data && typeof data.data === 'object') {
          if ('points' in data.data) return Number(data.data.points);
          if ('point' in data.data) return Number(data.data.point);
        }
      }
      
      console.warn('无法从API响应中提取积分数据，返回0');
      return 0;
    } catch (error) {
      console.error('获取积分出错:', error);
      return 0; // 出错时返回0而不是抛出异常
    }
  }

  static async getPointsHistory(username?: string): Promise<PointsTransaction[]> {
    const response = await fetch(`${API_BASE}/pointsRecord/recordList?page=1&size=10`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw { type: 'auth', code: error.message || 'UNKNOWN_ERROR' };
    }

    const data = await response.json();
    // 将后端PointsRecord转换为前端PointsTransaction格式
    return (data.records || []).map((record: any) => ({
      id: record.id.toString(),
      userId: record.userId.toString(),
      type: this.mapChangeTypeToTransactionType(record.changeType),
      points: record.changeType === 'CONSUME' ? -record.changeNum : record.changeNum,
      description: this.getDescriptionByChangeType(record.changeType),
      createdAt: record.recordTime
    }));
  }

  private static mapChangeTypeToTransactionType(changeType: string): 'upload' | 'download' | 'bonus' | 'penalty' {
    switch (changeType) {
      case 'RECHARGE': return 'upload';
      case 'CONSUME': return 'download';
      case 'BONUS': return 'bonus';
      default: return 'penalty';
    }
  }

  private static getDescriptionByChangeType(changeType: string): string {
    switch (changeType) {
      case 'RECHARGE': return '上传资源获得积分';
      case 'CONSUME': return '下载资源消耗积分';
      case 'BONUS': return '系统奖励积分';
      default: return '积分变动';
    }
  }

  static async banUser(username: string): Promise<void> {
    const response = await fetch(`${API_BASE}/users/${username}/ban`, {
      method: 'POST',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw { type: 'auth', code: error.message || 'UNKNOWN_ERROR' };
    }
  }

  static async unbanUser(username: string): Promise<void> {
    const response = await fetch(`${API_BASE}/users/${username}/unban`, {
      method: 'POST',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw { type: 'auth', code: error.message || 'UNKNOWN_ERROR' };
    }
  }

  static async getUserPosts(userId: number): Promise<any[]> {
    console.log('开始获取用户帖子，用户ID:', userId);
    try {
      const response = await fetch(`/api/posts/user/${userId}/with-comments`, {
        method: 'GET',
        headers: this.getHeaders(),
      });

      if (!response.ok) {
        console.error('获取用户帖子失败，状态码:', response.status);
        throw new Error(`获取用户帖子失败: ${response.statusText}`);
      }

      const data = await response.json();
      console.log('获取用户帖子成功，返回数据:', data);
      return data;
    } catch (error) {
      console.error('获取用户帖子出错:', error);
      return [];
    }
  }
}